<?php

class Label_model extends MY_Model {

    public function __construct() {
        parent::__construct();
        
        $this->table = 'jd_label';
    }
    
    public function records($limit = 0, $offset = 0, $conditions = array()) {
        $this->db->select('l.*,p.value AS parent_value,p.value_en AS parent_value_en');
        
        $this->db->from($this->table.' l');
        
        $this->db->join($this->table.' p','l.parent=p.id','left');

        if (!empty($conditions)) {
            foreach ($conditions as $condition) {
                $this->db->where('l.'.$condition[0], $condition[1]);
            }
        }

        if ($limit) {
            $this->db->limit($limit, $offset);
        }

        $this->db->order_by('l.parent');
        
        $this->db->order_by('l.order');

        $query = $this->db->get();

        return $query->result();
    }
    
    public function next_order($parent) {
        $this->db->select_max('`order`');

        $this->db->where('parent', $parent);

        $query = $this->db->get($this->table);

        $result = $query->row_object();

        return ($result ? $result->order : 0) + 1;
    }
    
    public function order($id, $new_order) {
        $label = $this->find($id);

        if ($label->order > $new_order) {
            $end_order = $label->order - 1;
            
            $sql = "update `{$this->table}` 
            set `order`=`order`+1 
            where `order`>={$new_order} 
            and `order`<={$end_order} 
            and `parent`='{$label->parent}';";
            
        } else {
            $start_order = $label->order + 1;
            
            $sql = "update `{$this->table}`
            set `order`=`order`-1 
            where `order`>='{$start_order}' 
            and `order`<='{$new_order}' 
            and `parent`='{$label->parent}';";
            
        }

        $this->db->query($sql);
        
        return $this->update($id, array('order' => $new_order));
    }
    
    public function delete_where($conditions){
        $this->db->from($this->table);

        if (!empty($conditions)) {
            foreach ($conditions as $condition) {
                $this->db->where($condition[0], $condition[1]);
            }
        }
        
        return $this->db->delete();
    }
}
